package cn.wolfcode.mq.listener;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.service.IOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ResultContext;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@RocketMQMessageListener(
        consumerGroup = "SeckillPendingOrderGroup",
        topic = MQConstant.ORDER_PENDING_TOPIC
)
@Component
@Slf4j
public class SeckillPendingOrderMessageListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void onMessage(OrderMessage orderMessage) {
        OrderMQResult result = new OrderMQResult();
        BeanUtils.copyProperties(orderMessage,result);
        try {
            log.info("[秒杀订单消费者] 收到秒杀订单前值消息：{}",orderMessage.toString());
            log.info("[秒杀订单消费者] 准备开始创建订单---------------------------------");
            //调用秒杀订单服务直接创建秒杀订单
            String orderNo = orderInfoService.doSeckill(orderMessage.getTime(), orderMessage.getSeckillId(), orderMessage.getToken());

            log.info("[秒杀订单消费者] 订单编号{}",orderNo);
            log.info("[秒杀订单消费者] 订单创建完成--------------");
            //创建订单成功
            result.setCode(Result.SUCCESS_CODE);
            result.setMsg("创建订单成功");
            result.setOrderNo(orderNo);
            rocketMQTemplate.asyncSend(MQConstant.ORDER_RESULT_SUCCESS_DEST, result, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("[秒杀订单消费者] 订单结果消息发送成功：{}",result.toString());
                }

                @Override
                public void onException(Throwable throwable) {
                    log.info("[秒杀订单消费者] 订单结果消息发送失败：{}",result.toString());
                }
            });
        } catch (BusinessException e) {
            //创建失败
            e.printStackTrace();
        }catch (Exception e) {
            //系统异常
            e.printStackTrace();
        }
    }
}
